package com.googlecode.perfectable.visuable.structure;

import static com.google.common.base.Preconditions.checkArgument;

import java.util.Iterator;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.google.common.collect.AbstractIterator;

public final class Elements {
	private static final class NodeIterable implements Iterable<Node> {
		private static final class NodeIterator extends AbstractIterator<Node> {
			private int current = 0;

			private final NodeList childNodes;

			public NodeIterator(NodeList childNodes) {
				this.childNodes = childNodes;
			}

			@Override
			protected Node computeNext() {
				Node item = this.childNodes.item(this.current);
				if(item == null) {
					return endOfData();
				}
				this.current += 1;
				return item;
			}
		}

		private final NodeList childNodes;

		NodeIterable(NodeList childNodes) {
			this.childNodes = childNodes;
		}

		@Override
		public Iterator<Node> iterator() {
			return new NodeIterator(this.childNodes);
		}
	}

	public static Iterable<Node> childNodes(Element element) {
		NodeList childNodes = element.getChildNodes();
		NodeIterable result = new NodeIterable(childNodes);
		return result;
	}

	public static void checkName(Element element, String elementName, String namespace) {
		checkArgument(elementName.equals(element.getLocalName()));
		checkArgument(namespace.equals(element.getNamespaceURI()));
	}

	private Elements() {

	}
}
